package com.cn.jx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cn.jx.common.controller.BaseController;
import com.cn.jx.manager.service.query.IUserServiceQry;
import com.jx.base.SessionUser;
import com.jx.enumType.OperatEnum;
import com.jx.util.Constant;
import com.jx.util.FormValidat;
import com.jx.util.MD5;
import com.jx.util.Response;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since 
 * <p>创建时间：2019年12月1日
 * <p>功能描述：登录操作
 * <p>官方网站：management/admin/index
 * <p>邮箱地址：524577360@qq.com
 */
@Controller
public class LoginController extends BaseController{
	 
	/**
	  *  读取属性配置文件 cookie设置
	*/
	@Value("${cookie.age:1}")
	private int age;
	
	/**
	 * 定义{@link IUserService userService <tt>用户操作接口</tt>}
	 */
	@Autowired
	protected IUserServiceQry userServiceQry;
	
	
	
	/**
	 * 
	* @Title:loginAdmin
	* @Description:TODO(跳转到跳转到后台管理登录界面)
	* <p>邮箱地址: 524577360@qq.com
	* String
	* @throws
	 */
	@RequestMapping("/login/page")
	public String loginAdmin(Model model, HttpServletRequest request, HttpServletResponse response) {

		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if (Constant.COOKIE_ADMIN_KEY.equals(cookie.getName())) {
				// 存在cookie
				try {
					String cvalue = URLDecoder.decode(cookie.getValue(), "UTF-8");
					Object obj = redisUtil.hget("LoginController", "doLoginAdmin[" + cvalue + "]");
					if (obj != null) {
						// 缓存中获取到设置到session中
						SessionUser objUser = JSONObject.parseObject(obj.toString(), SessionUser.class);
						request.getSession().setAttribute(Constant.SESSION_ADMIN_KEY, objUser);
						try {
							response.sendRedirect(request.getSession().getAttribute("base") + "/admin/index");
						} catch (IOException e) {
						}
					}
					model.addAttribute("loginNameRemeber", cvalue);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return "login";
	}
	 
 	

	/**
	 * 
	* @Title:doLoginAdmin
	* @Description:TODO(执行后台登录界面登录操作)
	* <p>邮箱地址: 524577360@qq.com
	* Response
	* @throws
	 */
	@RequestMapping("/login/dologin")
	@ResponseBody
	public Response doLoginAdmin(Model model, HttpServletRequest request, HttpServletResponse response, String userName,
			String password, String remember) {
		try {
			// 登陆验证
			FormValidat.validUser(userName, password);

			// 加密密码
			String md5Pwd = MD5.md52(password);

			// 登录操作
			SessionUser suser = userServiceQry.loginUser(userName, md5Pwd);

			// 登录成功 设置session cookie redis
			model.addAttribute(Constant.SESSION_ADMIN_KEY, suser);
			request.getSession().setAttribute(Constant.SESSION_ADMIN_KEY, suser);

			// cookie设置保存生命周期
			int cookieAge = "on".equals(remember) ? age * 60 * 60 : 0;
			Cookie cookie = new Cookie(Constant.COOKIE_ADMIN_KEY, URLEncoder.encode(suser.getLoginName(), "UTF-8"));
			cookie.setMaxAge(cookieAge);// 设置cookie的生命周期
			response.addCookie(cookie); // 添加cookie

			// redis保存
			String redissuser = JSONObject.toJSONString(suser);
			redisUtil.hsetLimitTime("LoginController", "doLoginAdmin[" + suser.getLoginName() + "]", redissuser, age,
					TimeUnit.HOURS);

			// 记录登录日志
			logUtil.LogMsg(SessionUser.class, suser.getUserId(), OperatEnum.LOGIN, suser.getLoginName());
			// 操作成功 返回
			return Response.Success(suser);
		} catch (Exception e) {
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:doLogOutAdmin
	* @Description:TODO(退出功能)
	* <p>邮箱地址: 524577360@qq.com
	* String
	* @throws
	 */
	@RequestMapping("/login/dologout")
	public String doLogOutAdmin(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String uid = "";
		String oper = "";
		// 先获取session登录对象
		Object obj = request.getSession().getAttribute(Constant.SESSION_ADMIN_KEY);
		if (obj != null) {
			SessionUser sessUser = (SessionUser) obj;
			uid = sessUser.getUserId();
			oper = sessUser.getLoginName();
			request.getSession().removeAttribute(Constant.SESSION_ADMIN_KEY);
			// 删除缓存
			redisUtil.hdelItem("LoginController", "doLoginAdmin[" + sessUser.getLoginName() + "]");
		} else {
			Cookie[] cookies = request.getCookies();
			for (Cookie cookie : cookies) {
				if (Constant.COOKIE_ADMIN_KEY.equals(cookie.getName())) {
					// 存在cookie
					String cvalue = URLDecoder.decode(cookie.getValue(), "UTF-8");
					// 删除缓存
					redisUtil.hdelItem("LoginController", "doLoginAdmin[" + cvalue + "]");
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
		}
		// 记录登录日志
		logUtil.LogMsg(SessionUser.class, uid, OperatEnum.LOGOUT, oper);
		// 操作成功 返回
		return "login";
	}
	
}
